import { BubbleMenu } from '@tiptap/react';
import { useEditorStore } from '@/store/useEditorZustand';
import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight';
import CodeBlock from '@tiptap/extension-code-block';
import ReactNode from '../CustomBlock';

const TextMenu = () => {
  const { editor } = useEditorStore();

  /*
: {
        editor: Editor
        view: EditorView
        state: EditorState
        oldState?: EditorState
        from: number
        to: number
      }
    */
  const shouldShow = (props) => {
    const { view, editor } = props;

    // 把不需要展示文字浮窗菜单的节点类型过滤掉
    if (
      [CodeBlockLowlight.name, CodeBlock.name, ReactNode.name].some((name) => editor.isActive(name))
    ) {
      return false;
    }

    if (!view || editor.view.dragging) {
      return false;
    }

    const {
      state: {
        doc,
        selection,
        selection: { empty, from, to },
      },
    } = editor;

    // 判断当前选中块是否是一个文本Node
    const isTextSelection = (selection) =>
      selection && selection.constructor && selection.constructor.name === 'TextSelection';

    const isEmptyTextBlock = !doc.textBetween(from, to).length && isTextSelection(selection);

    if (empty || isEmptyTextBlock || !editor.isEditable) {
      return false;
    }

    return true;
  };

  return (
    <BubbleMenu
      tippyOptions={{
        animation: 'fade',
        popperOptions: {
          placement: 'top-start',
          modifiers: [
            {
              name: 'preventOverflow',
              options: {
                boundary: 'viewport',
                padding: 8,
              },
            },
            {
              name: 'flip',
              options: {
                fallbackPlacements: ['bottom-start', 'top-end', 'bottom-end'],
              },
            },
          ],
        },
        maxWidth: 'calc(100vw - 16px)',
      }}
      pluginKey="text-menu"
      shouldShow={shouldShow}
      editor={editor}
    >
      TextMenu
      {/* render content */}
    </BubbleMenu>
  );
};

export default TextMenu;
